export const loadCurrentCity = () => {
	let city = null;
	try {
		const value = uni.getStorageSync('chooseCity');
		if (value) {
			city = value;
		}
	} catch (e) {
		// error
	}
	return city;
}

export const saveCurrentCity = (city, cb) => {
	if (!city) return;
	try {
		uni.setStorageSync('chooseCity', city);
	} catch (e) {
		//TODO handle the exception
	}
	cb && cb();
}
const mapkey = 'IZ3BZ-VQ3K2-XAMU4-CQ4PB-HQG6V-VIB5G';
const getLocationInfo = (cb) => { //2. 获取地理位置
	uni.getLocation({
		type: 'gcj02',
		success: res => {
			let latitude, longitude;
			latitude = res.latitude.toString();
			longitude = res.longitude.toString();
			uni.request({
				header: {
					"Content-Type": "application/text"
				},
				url: 'https://apis.map.qq.com/ws/geocoder/v1/?location=' + latitude + ',' + longitude + '&key=' + mapkey,
				success: re => {
					uni.setStorageSync("city", re.data.result.ad_info.city);
					cb && cb(re.data.result.ad_info.city);
				},
				fail: (res) => {
					cb && cb("全国");
				}
			});
		}
	});
}

export const startLocate = (cb) => {
	uni.authorize({
		scope: 'scope.userLocation',
		success: res => { //1.1 允许授权
			getLocationInfo(cb);
		},
		fail: res => { //1.2 拒绝授权
			console.log("你拒绝了授权，无法获得周边信息")
			cb && cb('全国');
		}
	})
}
